package com.leyou.item.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.leyou.common.enums.ExceptionEnum;
import com.leyou.common.exception.LyException;
import com.leyou.common.page.pageResult;
import com.leyou.common.utils.BeanHelper;
import com.leyou.item.dto.BrandDTO;
import com.leyou.item.entity.TbBrand;
import com.leyou.item.entity.TbCategoryBrand;
import com.leyou.item.mapper.TbBrandMapper;
import com.leyou.item.mapper.TbCategoryBrandMapper;
import com.leyou.item.service.TbBrandService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.leyou.item.service.TbCategoryBrandService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 品牌表，一个品牌下有多个商品（spu），一对多关系 服务实现类
 * </p>
 *
 * @author HM
 * @since 2019-10-25
 */
@Service
public class TbBrandServiceImpl extends ServiceImpl<TbBrandMapper, TbBrand> implements TbBrandService {


    @Autowired
    private TbBrandMapper brandMapper;

    @Autowired
    private TbCategoryBrandMapper CategoryBrandMapper;
   @Autowired
   private TbCategoryBrandService categoryBrandService;
    @Override
    public  pageResult<BrandDTO> findBrand(String key, Integer page, Integer rows, String sortBy, boolean desc) {
        IPage<TbBrand> pageInfo = new Page<>(page,rows);  // 查询第1页，每页返回5条
        /*创建查询条件对象*/
        QueryWrapper<TbBrand> queryWrapper=new QueryWrapper<>();
        /*参数：key：搜索查询的关键字：则采用模糊查询，like
        * 要先判断处理，key是否为null
        * 不为null：则为查询条件值
        * 为null:不再进行模糊查询
        *
        * */
        if(!StringUtils.isEmpty(key)){
            queryWrapper.lambda().like(TbBrand::getName,key);
            pageInfo.setCurrent(1);
            pageInfo.setSize(rows);
        }
        /*构建排序的条件:sortBy:排序的字段*/
        if(!StringUtils.isEmpty(sortBy)){
            /*排序的方式：升序，降序*/
            if(desc){
                queryWrapper.orderByDesc(sortBy);
            }else {
                queryWrapper.orderByAsc(sortBy);
            }
        }

        /*构建分页查询的条件：
        *1.创建Page对象，参数：当前页数page，每页显示的记录数rows
        *2.brandMapper.selectPage(page对象,queryWrapper查询条件);
        * IPage<TbBrand>   brandIPage = brandMapper.selectPage(pageInfo,queryWrapper);
        * 返回的结果集：IPage<TbBrand> 查询出来的数据
         * */

        IPage<TbBrand>  brandIPage = this.page(pageInfo,queryWrapper);

        /*1.判断查询出来的结果集是否为null
        2. 进行对象转换 TbBrand转为BrandDTO
        *
        * */
        if(brandIPage==null||CollectionUtils.isEmpty(brandIPage.getRecords())){
            /*如果：查询结果为null 或 查询出来的分页数据为null: 抛出异常*/
            throw new LyException(ExceptionEnum. BRAND_NOT_FOUND);
        }
        /*进行对象转换*/
        List<BrandDTO> brandDTOList = BeanHelper.copyWithCollection(brandIPage.getRecords(), BrandDTO.class);

       /*封装为分页查询的结果对象pageResult*/
        pageResult<BrandDTO> pageResult = new pageResult<>();
        pageResult.setTotalPage(brandIPage.getPages());
        pageResult.setTotal(brandIPage.getTotal());
        pageResult.setItems(brandDTOList);
        return pageResult;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void saveBrand(BrandDTO brandDTO, List<Long> cids) {
        /*将DTO对象转换为Tb对象*/
        TbBrand tbBrand = BeanHelper.copyProperties(brandDTO, TbBrand.class);
       /*主键自增:不用设置*/
        boolean save = this.save(tbBrand);
   /*     //方式一
        if(save){
         //因为：品牌与商品分类为多对多关联。当新增品牌时，还需要，添加中间表数据
            TbCategoryBrand categoryBrand=new TbCategoryBrand();
            for (Long cid : cids) {
                categoryBrand.setCategoryId(cid);
                *//*MybatisPlus中主键id设置为自增，在插入数据时没有对其赋值，要想获取插入后的
              数据的主键id值，可以直接在插入后通过Integer id = employee.getId();获取*//*
                categoryBrand.setBrandId(tbBrand.getId());
                int i = CategoryBrandMapper.insert(categoryBrand);
                if(i==0){
                    throw new LyException(ExceptionEnum.INSERT_OPERATION_FAIL);
                }
            }
        }else {
            //抛出异常
            // 新增失败，抛出异常
            throw new LyException(ExceptionEnum.INSERT_OPERATION_FAIL);
        }
*/
        //方式二
        if(save){
            List<TbCategoryBrand> list=new ArrayList<>();
            for (Long cid : cids) {
                TbCategoryBrand categoryBrand=new TbCategoryBrand();
                categoryBrand.setCategoryId(cid);
                /*MybatisPlus中主键id设置为自增，在插入数据时没有对其赋值，要想获取插入后的
              //数据的主键id值，可以直接在插入后通过Integer id = employee.getId();获取*/
                categoryBrand.setBrandId(tbBrand.getId());
                list.add(categoryBrand);
            }

            boolean saveBatch = categoryBrandService.saveBatch(list);
            if(!saveBatch){
                throw new LyException(ExceptionEnum.INSERT_OPERATION_FAIL);
            }
        }else {
            throw new LyException(ExceptionEnum.INSERT_OPERATION_FAIL);
        }
    }


    /*
    * 更新品牌数据
    * 1.修改品牌表的数据
    * 2.修改中间表的数据
    *
    * */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateBrand(BrandDTO brandDTO,List<Long> cids) {
        /*将DTO数据转化为TB数据*/
        TbBrand tbBrand = BeanHelper.copyProperties(brandDTO, TbBrand.class);
        /*更新品牌表数据*/
        boolean update = this.updateById(tbBrand);
        if(update){
            /*更新中间表数据：根据brand_id更新category_id*/
             QueryWrapper<TbCategoryBrand> queryWrapper=new QueryWrapper<>();
             queryWrapper.lambda().eq(TbCategoryBrand::getBrandId,tbBrand.getId());
            boolean remove = categoryBrandService.remove(queryWrapper);
            if(remove){
                List<TbCategoryBrand> list=new ArrayList<>();
                for (Long cid : cids) {
                    TbCategoryBrand categoryBrand=new TbCategoryBrand();
                    categoryBrand.setCategoryId(cid);
                /*MybatisPlus中主键id设置为自增，在插入数据时没有对其赋值，要想获取插入后的
              //数据的主键id值，可以直接在插入后通过Integer id = employee.getId();获取*/
                    categoryBrand.setBrandId(tbBrand.getId());
                    list.add(categoryBrand);
                }
                boolean saveBatch = categoryBrandService.saveBatch(list);
                if (!saveBatch){
                    throw new LyException(ExceptionEnum.UPDATE_OPERATION_FAIL);
                }
            }else {
                throw new LyException(ExceptionEnum.UPDATE_OPERATION_FAIL);
            }
        }else {
            throw new LyException(ExceptionEnum.UPDATE_OPERATION_FAIL);
        }

    }

    @Override
    public List<BrandDTO> findBrandByCategoryId(Long id) {
        /*根据分类id查询品牌
        * 1.先查询中间表
        * 2.在查询品牌表
        *两表联查，自己写SQL
        * */
        List<TbBrand> tbBrands = brandMapper.selectBrandByCategoryId(id);

        if(CollectionUtils.isEmpty(tbBrands)){
            throw new LyException(ExceptionEnum.BRAND_NOT_FOUND);
        }
        List<BrandDTO> brandDTOList = BeanHelper.copyWithCollection(tbBrands, BrandDTO.class);

        return brandDTOList;
    }
}



/*
   分页查询：条件构建
*   Page<TbBrand> page = new Page<>(page,rows);  // 查询第1页，每页返回5条
   IPage<TbBrand> iPage = BrandMapper.selectPage(page,queryWrapper);
*
* 主键回显：
*  MybatisPlus中主键id设置为自增，在插入数据时没有对其赋值，要想获取插入后的
 数据的主键id值，可以直接在插入后通过Integer id = employee.getId();获取
* */